package com.xzz.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.xzz.domain.MediaFile;
import com.xzz.service.IMediaFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import static java.nio.charset.StandardCharsets.UTF_8;

@Slf4j
@Component
@RocketMQMessageListener(topic = "message",
                        selectorExpression="sms",	//tags
                        consumerGroup = "service-media-consumer",
                        messageModel = MessageModel.CLUSTERING)//集群模式：一个消息被一个消费者消费
                         //还有广播模式：一个消息被多个同时消费
public class MessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMediaFileService mediaFileService;

    @Override
    @Transactional
    public void onMessage(MessageExt messageExt) {
        if(messageExt.getBody()==null){//防御编程
            return;
        }
        //真正消息在消息体里面
        String msg = new String(messageExt.getBody(), UTF_8);
        //可以用阿里的json object，string转任意类
        MediaFile mediaFile = JSONObject.parseObject(msg, MediaFile.class);
        //推流到服务器
        mediaFileService.handleFile2m3u8(mediaFile);
    }
}